package com.tengju.bff.interfaces.manage.crm.user.facade;

import com.beust.jcommander.internal.Maps;
import com.fasterxml.jackson.core.type.TypeReference;
import com.tengju.bff.interfaces.manage.crm.staff.sentiment.form.StaffSentimentRecordListQuery;
import com.tengju.bff.interfaces.shared.*;
import com.tengju.data.domain.shared.DateUtil;
import com.tengju.data.domain.shared.JsonUtil;
import com.tengju.user.domain.model.sentiment.SentimentRepository;
import com.tengju.user.domain.model.staff.StaffSentimentRecord;
import com.tengju.user.domain.model.user.SsoUserId;
import com.tengju.user.domain.model.user.UserIdCode;
import com.tengju.user.domain.shared.FormComponent;
import com.tengju.user.domain.shared.HtmlConvertUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class SentimentManageFacade {

    private final SentimentRepository sentimentRepository;

    @Value("${user.sentiment.details.form}")
    String sentimentDetailsFormModelString;



    public TableVO querySentimentRecordByPage(StaffSentimentRecordListQuery query) {
        TableVO tableVO = new TableVO();
        tableVO.setHeader(List.of(
                ColumnVO.of("createTime", "添加时间", false),
                ColumnVO.of("staffName", "添加人", false),
                ColumnVO.of("sentimentContext", "沟通内容", false)
        ));

        LocalDateTime startDayMin = DateUtil.getLocalDateOfDayMin(DateUtil.formatToLocalDate(query.getStartTime(), DateUtil.DATE_DAY_FORMAT));
        LocalDateTime nextDayMin = DateUtil.getLocalDateOfDayMin(DateUtil.formatToLocalDate(query.getEndTime(), DateUtil.DATE_DAY_FORMAT).plusDays(1));
        UserIdCode serviceProviderId = Optional.ofNullable(query.getServiceProviderId()).map(UserIdCode::new).orElse(null);
        List<SsoUserId> ssoUserIdList = Optional.ofNullable(query.getSsoUserIds()).map(v -> v.stream().filter(Objects::nonNull).distinct().map(SsoUserId::new).collect(Collectors.toList())).orElse(Collections.emptyList());
        int offset = query.getOffset();
        int total = sentimentRepository.getStaffSentimentRecordTotal(ssoUserIdList, startDayMin, nextDayMin, serviceProviderId);
        if (offset > total) {
            return tableVO;
        }
        List<StaffSentimentRecord> staffSentimentRecordList = sentimentRepository.getStaffSentimentRecordPageList(ssoUserIdList, startDayMin, nextDayMin,
                serviceProviderId, query.getOffset(), query.getPageSize());
        List<Map<String, Object>> records = com.beust.jcommander.internal.Lists.newArrayList();
        if (CollectionUtils.isEmpty(staffSentimentRecordList)) {
            return new TableVO();
        }
        for (StaffSentimentRecord staffSentimentRecord : staffSentimentRecordList) {
            Map<String, Object> row = Maps.newHashMap();
            row.put("createTime", DateUtil.formatLocalDateTime(DateUtil.DATE_TIME_FORMAT, staffSentimentRecord.getCreateTime()));
            row.put("staffName", staffSentimentRecord.getOperator());
            List<FormComponent> formComponentList = JsonUtil.toList(staffSentimentRecord.getSentimentContext(), new TypeReference<>() {});
            if (CollectionUtils.isEmpty(formComponentList)){
                formComponentList = Collections.emptyList();
            }
            List<FormComponent> talkContent = formComponentList.stream().filter(v -> "talkContent".equals(v.getCode())).collect(Collectors.toList());
            row.put("sentimentContext", HtmlConvertUtil.delHtmlTagAndDealImgAndVideo(talkContent.get(0).getFilledData().toString(),100));
            row.put("sentimentId", staffSentimentRecord.getSentimentId());
            row.put("ssoUserId", staffSentimentRecord.getSsoUserId());
            records.add(row);
        }
        tableVO.setRecords(records);
        tableVO.setPage(PageResultVO.of(query.getPageIndex(), query.getPageSize(), total));
        return tableVO;
    }


}
